<?php

/**
 * @Author: CraspHB彬
 * @Date:   2018-02-24 14:24:47
 * @Email:   646054215@qq.com
 * @Last Modified time: 2018-02-24 20:31:47
 */
namespace app\admin\controller;
use think\Controller;
class Umeditor extends Controller{
	protected $config;
	protected $path;
	public function _initialize(){
		$CONFIG = json_decode(preg_replace("/\/\*[\s\S]+?\*\//", "", file_get_contents("./public/umeditor/php/config.json")), true);
		$upload_path=config('web_upload.upload_path')?config('web_upload.upload_path'):'./upload';
		$this->path = $upload_path;
        $this->config = $CONFIG;
	}
    /**
     * 上传
     * @return [type] [description]
     */
    public function upload(){
    	date_default_timezone_set("Asia/chongqing");
		error_reporting(E_ERROR);
		header("Content-Type: text/html; charset=utf-8");
        $CONFIG = $this->config;
		
		$action = $_GET['action'];
		switch ($action) {
		    case 'config':
		        $result = json_encode($CONFIG);
		        break;

		    /* 上传图片 */
		    case 'uploadimage':
		       $this->_upload_editor(['type'=>'img','size'=>1024*1024*10,'ext'=>'png,jpg,jpeg,gi,bmp']);
		       break;
		    /* 上传涂鸦 */
		    case 'uploadscrawl':
			   $this->uploadscrawl();
		       break;		    
		    /* 上传视频 */
		    case 'uploadvideo':
		       $this->_upload_editor(['type'=>'video','size'=>1024*1024*100,'ext'=>'flv,mkv,avi,rmvb,mp4,wav']);
		       break;	
		    /* 上传文件 */
		    case 'uploadfile':
		        $this->_upload_editor(['type'=>'file','size'=>1024*1024*20,'ext'=>'rar,zip,tar,gz,7z,bz2,doc,docx,xls,xlsx,ppt,pptx,pdf,txt']);
		        break;

		    /* 列出图片 */
		    case 'listimage':
		        $this->_list_editor();
		        break;
		    /* 列出文件 */
		    case 'listfile':
		        $this->_list_editor();
		        break;

		    /* 抓取远程文件 */
		    case 'catchimage':
		        $this->_catch_editor();
		        break;

		    default:
		        $result = json_encode(array(
		            'state'=> '请求地址出错'
		        ));
		        break;
		}

		/* 输出结果 */
		if (isset($_GET["callback"])) {
		    if (preg_match("/^[\w_]+$/", $_GET["callback"])) {
		        echo htmlspecialchars($_GET["callback"]) . '(' . $result . ')';
		    } else {
		        echo json_encode(array(
		            'state'=> 'callback参数不合法'
		        ));
		    }
		} else {
		    echo $result;
		    exit();
		}
    }
    /**
     * 文件上传
     * @param  [type] $config [description]
     * @return [type]         [description]
     */
    public function _upload_editor($config){
    	 $config = array_merge($this->config,$config);
         $file = request()->file('upfile');
         $filePath = $this->path;
	    // 移动到框架应用根目录/public/uploads/ 目录下
	    if($file){
	        $info = $file->validate(['size'=>$config['size'],'ext'=>$config['ext']])->move($filePath . DS . 'umeditor'.'/'.$config['type']);
	        if($info){
				$img_url=$filePath . DS . 'umeditor' . '/'.$config['type'].'/'. $info->getSaveName();
				$title =$info->getFilename();
				$state = 'SUCCESS';
				$url= config('view_replace_str.__ROOT__').substr($img_url,1);
	        }else{
	            // 上传失败获取错误信息
	            $state = $file->getError();
	        }
	    }
	    $response=array(
			"state" => $state,
			"url" => $url,
			"title" => $title,
			"original" =>$title,
		);
		echo json_encode($response);
    }
    /**
     * 涂鸦
     * @return [type] [description]
     */
    public function uploadscrawl(){

		$data = input('post.' . $this->config ['scrawlFieldName']);
        $url='';
        $title = '';
        $oriName = '';
		if (empty ($data)) {
			$state= 'Scrawl Data Empty!';
		} else { 
		$img = base64_decode($data);
		$savepath = $this->get_img('png', $img);
		if ($savepath) {
			$state = 'SUCCESS';
			$url = config('view_replace_str.__ROOT__').substr($savepath,1);
		} else {
			$state = 'Save scrawl file error!';
		}
		}
		$response=array(
		"state" => $state,
		"url" => $url,
		"title" => $title,
		"original" =>$oriName ,
		);
		echo json_encode($response);
    }
    /**
     * base64编码图片保存病返回路径
     * @param  [type] $ext     [description]
     * @param  [type] $content [description]
     * @return [type]          [description]
     */
    public function get_img($ext = null, $content = null){
	    $newfile = '';
	    $path=$this->path;
	    if ($ext && $content) {
	        do {
	            $newfile = $path.'/umeditor/img/'.date('Ymd/') . uniqid() . '.' . $ext;
	        } while (file_exists($newfile));
	        $dir = dirname($newfile);
	        if (!is_dir($dir)) {
	            mkdir($dir, 0777, true);
	        }
	        file_put_contents($newfile, $content);
	    }
	    return $newfile;
	}
	public function _list_editor(){
		$config = $this->config;
		$upload_path = $this->path;
		/* 判断类型 */
		switch ($_GET['action']) {
		    /* 列出文件 */
		    case 'listfile':
		        $allowFiles = $config['fileManagerAllowFiles'];
		        $listSize = $config['fileManagerListSize'];
		        $path = $upload_path.'/umeditor/file/' ;
		        break;
		    /* 列出图片 */
		    case 'listimage':
		    default:
		        $allowFiles = $config['imageManagerAllowFiles'];
		        $listSize = $config['imageManagerListSize'];
		        $path = $upload_path.'/umeditor/img/' ;
		}
		$allowFiles = substr(str_replace(".", "|", join("", $allowFiles)), 1);

		/* 获取参数 */
		$size = isset($_GET['size']) ? htmlspecialchars($_GET['size']) : $listSize;
		$start = isset($_GET['start']) ? htmlspecialchars($_GET['start']) : 0;
		$end = $start + $size;
		/* 获取文件列表 */
		$path = $_SERVER['DOCUMENT_ROOT'] .config('view_replace_str.__ROOT__'). substr($path, 1);
		$files = $this->getfiles($path, $allowFiles);
		if (!count($files)) {
		    return json_encode(array(
		        "state" => "no match file",
		        "list" => array(),
		        "start" => $start,
		        "total" => count($files)
		    ));
		}

		/* 获取指定范围的列表 */
		$len = count($files);
		for ($i = min($end, $len) - 1, $list = array(); $i < $len && $i >= 0 && $i >= $start; $i--){
		    $list[] = $files[$i];
		}
		//倒序
		//for ($i = $end, $list = array(); $i < $len && $i < $end; $i++){
		//    $list[] = $files[$i];
		//}

		/* 返回数据 */
		$result = json_encode(array(
		    "state" => "SUCCESS",
		    "list" => $list,
		    "start" => $start,
		    "total" => count($files)
		));

		echo $result;
	}
	/**
	 * 遍历获取目录下的指定类型的文件
	 * @param $path
	 * @param array $files
	 * @return array
	 */
	public function getfiles($path, $allowFiles, &$files = array()){
	    if (!is_dir($path)) return null;
	    if(substr($path, strlen($path) - 1) != '/') $path .= '/';
	    $handle = opendir($path);
	    while (false !== ($file = readdir($handle))) {
	        if ($file != '.' && $file != '..') {
	            $path2 = $path . $file;
	            if (is_dir($path2)) {
	                $this->getfiles($path2, $allowFiles, $files);
	            } else {
	                if (preg_match("/\.(".$allowFiles.")$/i", $file)) {
	                    $files[] = array(
	                        'url'=> substr($path2, strlen($_SERVER['DOCUMENT_ROOT'])),
	                        'mtime'=> filemtime($path2)
	                    );
	                }
	            }
	        }
	    }
	    return $files;
	}
}